﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MediaArtAggregator.Core.com.amazon.webservices;
using MediaArtAggregator.Core.Configuration;

namespace MediaArtAggregator.Core.SearchProvider {
  public class AmazonSearchSource : ApiBasedSearchSource {
    public override void Search ( string search, Settings settings, SearchType searchType ) {
      this.OnSearchInitialize ( EventArgs.Empty );
      AWSECommerceService service = new AWSECommerceService ( );
      string accessKey = "19E67D8P1XK8M0D3K7G2";
      string associateTag = "camalotdesign-20";
      ItemSearch itemSearch = new ItemSearch ( );
      itemSearch.AWSAccessKeyId = accessKey;
      itemSearch.SubscriptionId = accessKey;
      itemSearch.AssociateTag = associateTag;
      ItemSearchRequest request = new ItemSearchRequest ( );

      request.ResponseGroup = new string[ ] { "Images" };
      request.SearchIndex = "All";
      //request.Title = search;
      string type = searchType.Name;
      if ( string.Compare ( type, "generic", true ) == 0 )
        type = string.Empty;
      request.Keywords = string.Format ( "{0} {1}", search, type ).Trim ( );
      itemSearch.Request = new ItemSearchRequest[ ] { request };

      ItemSearchResponse response = service.ItemSearch ( itemSearch );
      if ( response.Items[ 0 ].Item != null ) {
        foreach ( Item item in response.Items[ 0 ].Item ) {
          if ( item.LargeImage != null && !string.IsNullOrEmpty ( item.LargeImage.URL ) )
            this.Results.Add ( new Uri ( item.LargeImage.URL ) );
          else {
            if ( item.MediumImage != null && !string.IsNullOrEmpty ( item.MediumImage.URL ) )
              this.Results.Add ( new Uri ( item.MediumImage.URL ) );
            else {
              if ( item.SmallImage != null && !string.IsNullOrEmpty ( item.SmallImage.URL ) )
                this.Results.Add ( new Uri ( item.SmallImage.URL ) );
            }
          }
        }
      }
      this.OnSearchComplete ( EventArgs.Empty );
    }

    public override string ToString ( ) {
      return "amazon.com";
    }
  }
}
